package com.wc.data_structures.linkedlist;

/**
 * @Author congge
 * @Date 2023/4/18 22:12
 * @description 单链表练习
 */
public class SingleLinkedListDemo {

}

class SingleLinkedList<T> {
    private final Node<T> head;

    public SingleLinkedList() {
        head = new Node<T>();
    }

    /**
     * 将node节点加入到链表尾部
     *
     * @param node
     */
    public void addNode(Node<T> node) {
        Node<T> tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = node;
    }

    /**
     * 将node节点添加到链表头部
     *
     * @param node
     */
    public void addHeadNode(Node<T> node) {
        addNodeNext(head, node);
    }


    /**
     * 将node2节点添加到node1节点后面
     *
     * @param node1
     * @param node2
     */
    public void addNodeNext(Node<T> node1, Node<T> node2) {
        node2.next = node1.next;
        node1.next = node2;
    }


    /**
     * 删除节点
     *
     * @param preNode 待删除节点的前一个节点
     */
    public void deleteNode(Node<T> preNode) {
        preNode.next = preNode.next.next;
    }

    /**
     * 获得该链表有效节点的个数
     *
     * @return
     */
    public int size() {
        int size = 0;
        Node<T> tmp = head;
        while (tmp.next != null) {
            size++;
            tmp = tmp.next;
        }
        return size;
    }

    // 显示链表
    public void showNode() {
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        Node<T> tmp = head.next;
        while (tmp != null) {
            System.out.print(tmp.next.value.toString() + " ");
            tmp = tmp.next;
        }
        System.out.println();
    }
}

// 对象就是节点
class Node<T> {
    public T value;
    public Node<T> next;

    public Node() {

    }

    public Node(T value) {
        this.value = value;
    }

    public Node(T value, Node<T> next) {
        this.value = value;
        this.next = next;
    }
}
